import java.util.EnumSet;

import javax.servlet.DispatcherType;
import javax.servlet.MultipartConfigElement;

import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.webapp.WebAppContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.control.UploadTomcat;
import com.filter.MyFilter;

import com.servlet.My;

import hyl.core.MyFun;
import hyl.core.io.MyPath;

public class StartServer {

	private static Logger logger = LoggerFactory.getLogger(StartServer.class);

	public static void main(String[] args) {
		Server server = new StartServer().createServer();
		try {
			server.start();
			// System.out.println("文件服务器开启！！！");
			logger.info("文件服务器开启！！！");
			server.join();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private StartServer() {
	}

	private Server createServer() {
		// jetty server 默认的最小连接线程是8，最大是200，连接线程最大闲置时间60秒
		My.getInstance();
		int port = MyFun.str2int(My.getConst("UPLOAD_PORT"));
		port = (port == 0) ? 8080 : port;
		logger.info("文件服务监听端口=" + port);
		Server server = new Server();

		ServerConnector connector = new ServerConnector(server);
		connector.setPort(port);
		server.setConnectors(new Connector[] { connector });
		String webappPATH = MyPath.sfind("webapp");
		WebAppContext webAppContext = new WebAppContext();
		webAppContext.setContextPath("/"); // 虚拟目录
		System.out.println("webapp路径=" + webappPATH);
		// webAppContext.setDescriptor(webappPATH+"WEB-INF/web.xml");
		webAppContext.setResourceBase(webappPATH);
		webAppContext.setDisplayName("hyl-fileserver");
		webAppContext.setClassLoader(this.getClass().getClassLoader());
		webAppContext.setConfigurationDiscovered(true);
		webAppContext.setParentLoaderPriority(true);
		// webAppContext.addEventListener(new StartUpListener()); 可直接在web.xml中配置
		// 不可以用jsp
		// 支持 jsp////
		/*
		 * File temp = new File("webapp/temp");
		 * 
		 * webAppContext.setTempDirectory(temp);
		 * 
		 * webAppContext.setAttribute("org.eclipse.jetty.containerInitializers",
		 * 
		 * Arrays.asList(new ContainerInitializer(new JasperInitializer(), null)));
		 * 
		 * webAppContext.setAttribute(InstanceManager.class.getName(), new
		 * SimpleInstanceManager());
		 */
		////
		ServletHolder fileUploadServletHolder = new ServletHolder(new UploadTomcat());
		fileUploadServletHolder.getRegistration().setMultipartConfig(new MultipartConfigElement(""));
		// 添加文件上传请求路由
		webAppContext.addServlet(fileUploadServletHolder, "/upload");
		// 分布式文件下载路径
		webAppContext.addServlet(com.control.DownloadDFSControl.class, "/down/df/*");
		// 非分布式文件下载路径
		webAppContext.addServlet(com.control.DownloadControl.class, "/down/f/*");
		// 过滤器 跨域处理 编码处理
		webAppContext.addFilter(MyFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));// 串行处理
		server.setHandler(webAppContext);
		return server;
	}

}
